<?php
$relPath="./../../pinc/";
require_once $relPath."dpinit.php";
include_once($relPath.'dp_main.inc');

$projectid          = ArgProjectId();
// $username           = Arg("username");
$pagename           = Arg("pagename");
$pagenames          = ArgArray('pagenames');
$pagenames          = array_keys($pagenames);
$todo               = Arg("todo");
$is_my_pages        = IsArg("my_pages");

$User->IsLoggedIn()
    or redirect_to_home();

$project = new DpProject($projectid);

if($todo == "deletePages") {
    // dump("delete");
    // dump($pagenames);
    $project->DeletePages($pagenames);    
}

if($todo == "clearPages") {
    dump("clear");
    dump($pagenames);
    $project->ClearPages($pagenames);    
}
if($todo == "deletePage") {
    // dump("delete");
    // dump($pagename);
    $project->DeletePage($pagename);    
}
if($todo == "clearPage") {
    // dump("clear");
    // dump($pagename);
    $project->ClearPage($pagename);    
}

if($todo == "pageLogs") {
    $url = url_for_page_log($projectid, $pagenames);
    window.open($url);
    exit;
}

$title = $project->Title();
$page_title = _('Page details: ').$title;

dp_header($page_title);

echo "
    <div class='w25 left'>
    ".link_to_project($projectid, "Return to project page")."<br>
    ".($is_my_pages
        ? link_to_page_detail($projectid, "Show all pages")
        : link_to_page_detail_mine($projectid, "Show your pages"))."
    </div>
    <style type='text/css'>
        .package {
            text-align: center;
        }
        .shrink-to-fit {
            padding: .5em 2.5em;
            display: inline-block;
        }
        .lfloat {
            float: left;
        }
        .rfloat {
            float: right;
        }
    </style>
    <div class='package'>
    <h1>$title</h1>

    <form name='pagesform' id='pagesform' action='' 
                    method='POST'  onclick='eFormClick(event)'>
    <input type='hidden' id='projectid' name='projectid'
                                        value='{$projectid}' />
    <input type='hidden' id='pagename' name='pagename' value='' />
    <input type='hidden' id='todo' name='todo' value='' />";

if($project->UserMayManage()) {
    echo "
    <div class='shrink-to-fit'>
        <input type='button' value='Clear selected' 
                                        onclick='eClearPages()'/>
        <input type='button' value='Delete selected'
                                    onclick='eDeletePages()'/>
        <input type='button' value='View logs'
                                    onclick='eViewLogs()'/>
    </div>\n";
}

echo_pagetable($project, $is_my_pages);
echo "
    </form>
    </div>
</div> <!-- package -->\n";

html_footer();
exit;

function echo_pagetable($project, $is_my_pages) {
    global $projects_dir, $pm_url;
    global $dpdb;
    global $User;
    global $ok;
    
    $projectid = $project->ProjectId();
    $tblrows = page_table_rows($project, $is_my_pages);

    echo_js($tblrows);

    $tbl = new DpTable();
    $tbl->SetClass("em90");
    $tbl->SetId("tblpages");

    if($project->UserMayManage()) {
        $tbl->AddCaption(null, 4);  // leave one for the rownumber?
        $tbl->AddColumn(chk_caption(), null, "rowchkbox", "width: 4em");
    }
    else {
        $tbl->AddCaption(null, 3); 
    }

    $tbl->AddColumn("^"._("Page"), null, "imagelink", "skinny");
    $tbl->AddColumn("^"._("Text"), null, "mastertextlink", "skinny");
    $tbl->AddColumn("^"._("Status"), null, "pagestate", "w4em");

    $i = 0;
    foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid) {
        $i++;
        $tbl->AddCaption("^".$roundid, 
                    $project->UserMayManage() ? 4 : 3);
        $tbl->AddColumn("^"._("Diff"), "$roundid", "difflink");
        $tbl->AddColumn("^"._("Date"), "time_{$i}", "roundtime");
        if($project->UserMayManage()) {
            $tbl->AddColumn("^"._("User"), 
                                "$roundid", "usrlnk", "nopad");
        }
        $tbl->AddColumn(">"._("Text"), "r{$i}", "textlink");
        if($roundid == $project->RoundId())
            break;
    }

    if($project->UserMayManage()) {
        $tbl->AddCaption("^"._("For PM"), 4);
        $tbl->AddColumn("^"._("Clear"), null, "clearlink");
        $tbl->AddColumn("^"._("Fix"), null, "fixlink");
        $tbl->AddColumn("^"._("Edit"), null, "editlink");
        if($User->IsSiteManager() || $project->UserIsPM()) {
            $tbl->AddColumn("^"._("Delete"), null, "deletelink");
        }
    }
    else {
        $tbl->AddCaption("^".("Your<br/>pages"));
        $tbl->AddColumn("^"._("Edit"), "$roundid", "usreditlink");
    }

    $tbl->SetRows($tblrows);
    $tbl->EchoTableNumbered();
}

function chk_caption() {
    return "All <input type='checkbox' name='ckall' 
                onclick='CheckAll();'>";
}

function page_table_rows($project, $is_my_pages) {
    global $dpdb;
    global $User;

    $projectid = $project->ProjectId();
    $roundid = $project->RoundId();
    $roundindex = RoundIndexForId($roundid);

    $myname = $User->Username();
    
    $sql = "
        SELECT  
            '$projectid' as projectid,
            '$roundid' as roundid,
            pp.fileid AS pagename,
            pp.image AS imagefile,
            pp.state AS pageroundstate,
            p.state AS projectroundstate,
            SUBSTRING(p.state, 1, 2) AS projectroundid,
            CHAR_LENGTH(pp.master_text) AS textlength_master,\n";

    $this_roundid = $project->RoundId();
    $i = 1;
    foreach(RoundIdsInOrder($project->SequenceCode()) as $roundid) {
        $textfield = TextFieldForRoundIndex($i); 
        $prevtextfield = TextFieldForRoundIndex($i-1);
        $sql .= "
            pp.Round{$i}_user AS user_{$i},
            pp.Round{$i}_time AS time_{$i},
            CHAR_LENGTH(pp.Round{$i}_text) AS textlength_{$i},
            CASE WHEN BINARY pp.$textfield = BINARY pp.$prevtextfield 
                THEN 0 ELSE 1 END AS is_diff_{$i},\n";
        $i++;
    }

    $sql .= "
            pp.b_user,
            pp.b_code
        FROM pages AS pp
        JOIN projects AS p
            ON pp.projectid = p.projectid
        WHERE
            pp.projectid = '{$project->ProjectId()}'\n"
        .($is_my_pages 
        ? "AND (
            pp.round1_user = '$myname'
            OR pp.round1_user = '$myname'
            OR pp.round2_user = '$myname'
            OR pp.round3_user = '$myname'
            OR pp.round4_user = '$myname'
            OR pp.round5_user = '$myname'
            OR pp.round6_user = '$myname'
            OR pp.round7_user = '$myname'
            OR pp.round8_user = '$myname'
            OR pp.round9_user = '$myname'
            OR pp.round10_user = '$myname'
        )\n"
        : "")
        ." ORDER BY fileid\n";
    // say(PrettySql($sql));
    $rows = $dpdb->SqlRows($sql);
    return $rows;
}

function rowchkbox($pagerow) {
    $name = 'pagenames['.$pagerow['pagename'].']';
    return "<input type='checkbox' name='$name'>";
}

function imagelink($pagerow) {
    $projectid  = $pagerow['projectid'];
    $pagename   = $pagerow['pagename'];

    return $pagerow['imagefile']
        ? link_to_display_image($projectid, $pagename, $pagename)
        : "<span class='danger'>"._("NO IMG!")."</span>";
}

function mastertextlink($pagerow) {
    global $pm_url;
    $url = unamp("$pm_url/downloadproofed.php"
        ."?projectid={$pagerow['projectid']}"
        ."&pagename={$pagerow['pagename']}"
        ."&roundid=OCR");
    $ret = "<a target='_blank' href='{$url}"
        ."'>{$pagerow['textlength_master']}</a>";
    return $ret;
}

function textlink($idx, $pagerow) {
    global $pm_url, $User;
    $idx = substr($idx, 1);
    $roundid = RoundIdForIndex($idx);
    $key = "textlength_{$idx}";
    if(! isset($pagerow[$key]))
        return "";
    $url = unamp("$pm_url/downloadproofed.php"
            . "?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&roundid={$roundid}");
    $rindex = RoundIndexForId($roundid);
    $userval = $pagerow["user_{$rindex}"];
    $myclass = ($userval == $User->Username()
            ? " class='red'"
            : " ");
    return "<a $myclass target='_blank' href='$url"
            . "'>".$pagerow[$key]."</a>";
}

function pgstat($pagerow) {
    $rs = $pagerow['pageroundstate'];
    return preg_replace("/^.+?_/", "", $rs);
}

function pagestate($pagerow) {
    $stat = pgstat($pagerow);
    if($stat == "out" || $stat == "temp") {
        $roundid = $pagerow['roundid'];
        $index = RoundIndexForId($roundid);
        $timefield = sprintf("time_%d", $index);
        $ptime = $pagerow[$timefield];
        $rsvtime = 4 * 60 - minutes_ago($ptime);
        if($rsvtime > 0) {
            $s_time = sprintf("%d:%2d", 
                            $rsvtime/60, $rsvtime%60);
        }
    }

    switch($stat) {
        case "avail":
            return "<div class='pg_available'>$stat</div>\n";

        case "bad":
            return "<div class='danger'>$stat</div>\n";

        case "out":
        case "temp":
            // return $rsvtime > 0
                // ? "<div class='status_out'>$s_time</div>\n"
                // : "<div class='status_avail'>avail</div>\n";
            return "<div class='pg_out'>out</div>\n";

        case "saved":
            return "<div class='pg_completed'>$stat</div>\n";

        default:
            return $stat;
    }
}

function roundtime($val, $page) {
    return $val == 0
        ? ""
        : strftime( "%x %H:%M", intval($val) );
}

function clearlink($pagerow) {
    $roundid = $pagerow['projectroundid'];  // e.g. P2a
    $id = RoundIndexForId($roundid);        // 3
    $key = "textlength_{$id}";              // e.g. textlength_3
    $pgstate = $pagerow['pageroundstate'];  // e.g. P2a.page_avail
    if(right($pgstate, 10) == "page_avail") {
        return "";
    }
    return "<span id='{$pagerow['pagename']}'
                    class='likealink'>"._("Clear")."</a>";
    // global $pm_url;
    // $url = unamp("$pm_url/edit_pages.php"
            // ."?projectid={$pagerow['projectid']}"
            // . "&pagename={$pagerow['pagename']}"
            // . "&operation=clear");
    // return "<a href='{$url}'>"._("Clear")."</a>";
}

function fixlink($pagerow) {
    if(pgstat($pagerow) != "bad")
        return "";
    return link_to_proof_page($pagerow['projectid'],
                                    $pagerow['pagename'], "Fix");
    // global $pm_url;
    // $fix = _("Fix");

    // $url = unamp("$pm_url/handle_bad_page.php"
            // ."?projectid={$pagerow['projectid']}"
            // . "&pagename={$pagerow['pagename']}");
    // return "<a target='_blank' href='{$url}'>$fix</a>";
}

function editlink($row)
{
    global $proof_url;
    global $project;

    if($project->UserMayManage()) {
        $edit = _("Edit");
        return link_to_proof_page($row['projectid'],
                                  $row['pagename'],
                                  $edit);
        /*
        $url = "$proof_url/proof.php"
                ."?projectid={$row['projectid']}"
                . "&pagename={$row['pagename']}";
        return "<a target='_blank' href='{$url}'>$edit</a>";
        */
    }
    else {
        return "";
    }
}

function usreditlink($roundid, $row) {
    global $project;
    global $proof_url;
    global $User;

    if($roundid != $project->RoundId())
        return "";
    // $match_username = $row['match_username'];
    $rindex = RoundIndexForId($roundid);
    $userval = $row["user_{$rindex}"];
    if($User->Username() != $userval)
        return "";
    $projectid = $project->ProjectId();
    $pagename = $row['pagename'];
    return link_to_proof_page($projectid, $pagename, "edit");
}

function deletelink($pagerow) {
    // global $pm_url;
    // $url = unamp("$pm_url/edit_pages.php"
            // ."?projectid={$pagerow['projectid']}"
            // . "&pagename={$pagerow['pagename']}"
            // . "&operation=delete");
    return "<span id='{$pagerow['pagename']}'
                    class='likealink'>"._("Delete")."</a>";
}

function difflink($rindex, $pagerow) {
    global $pm_url;
    // dump($rindex);
    // dump($pagerow);
    // $id = RoundIndexForId($pagerow['roundid']);
    $id = RoundIndexForId($rindex);
    $key = "textlength_{$id}";
    if(! isset($pagerow[$key]) || $pagerow[$key] == 0)
        return "";
    $key = "is_diff_{$id}";
    if( $pagerow[$key] == 0)
        return "no diff";

    $url = unamp("$pm_url/diff.php"
            ."?projectid={$pagerow['projectid']}"
            . "&pagename={$pagerow['pagename']}"
            . "&roundid={$rindex}");
    return "<a target='_blank' href='{$url}'>diff</a>";
}

function pageroundid($pagerow) {
    return preg_replace("/\..*$/", "", $pagerow['pageroundstate']);
}

function usrlnk($roundid, $page) {
    global $User;
    $rindex = RoundIndexForId($roundid);
    $key = "user_{$rindex}";
    $proofername = $page[$key];
    // index for current round
    $pindex = RoundIndexForId(pageroundid($page));

    if($proofername == "")
        return "";

    if($User->Username() != $proofername) {
        return "<div class='notmypage'>$proofername</div>";
    }

    // current round?
    if($rindex != $pindex) {
        return "<div class='mypagedone'>$proofername</div>";
    }

    // based on page state ...
    switch(pagestate($page)) {
        case "out":
        case "temp":
            return "<div class='mypageopen'>$proofername</div>"; 
        case "saved":
            return "<div class='mypagesaved'>$proofername</div>";
        default:
            return "<div class='mystery'>$proofername</div>";
    }
}

function echo_js($rows) {
    $num_rows = count($rows);
    
    ?>
<script>

    var _cks;

    function $(id) {
        return document.getElementById(id);
    }

    var avail_pages = [
    <?php 
    foreach($rows as $row) {
        if(pagestate($row) == 'avail') {
            echo "'{$row['pagename']}', ";
            // echo "avail_pages.push('{$row['pagename']}')\n";
        }
    }
    ?>];
    var i;

    function checked_count() {
        var n = 0;
        var pgchecks = $('tblpages').getElementsByTagName('input');
        for(var i = 0; i < pgchecks.length; i++) {
            if(pgchecks[i].checked) {
                n++;
            }
        }
        return n;
    }

    function eDeletePages() {
        var n = checked_count();
        if(n == 0) {
            return false;
        }
        if(! window.confirm('Confirm you want to delete page ' 
                                    + n.toString() + ' pages')) {
            return false;
        }
        $('todo').value = 'deletePages';
        $('pagesform').submit();
        return true;
    }

    function eClearPages() {
        var n = checked_count();
        if(n == 0) {
            return false;
        }
        if(! window.confirm('Confirm you want to clear '
                                + n.toString() + ' pages')) {
            return false;
        }
        $('todo').value = 'clearPages';
        $('pagesform').submit();
        return true;
    }

    function eViewLogs() {
        var n = checked_count();
        if(n == 0) {
            return false;
        }
        $('pagesform').target = '_blank';
        $('pagesform').action = 'pagelog.php';
        $('pagesform').submit();
        return true;
    }

    function eDeletePage(name) {
        if(! window.confirm('Confirm you want to delete page ' 
                                                        + name)) {
            return false;
        }
        $('pagename').value = name;
        $('todo').value = 'deletePage';
        $('pagesform').submit();
        return true;
    }

    function eClearPage(name) {
        if(! window.confirm('Confirm you want to clear page ' 
                                                        + name)) {
            return false;
        }
        $('pagename').value = name;
        $('todo').value = 'clearPage';
        $('pagesform').submit();
        return true;
    }

    function ePageLog(name) {
        $('pagename').value = name;
        $('todo').value = 'clearPage';
        $('pagesform').submit();
    }

    function eFormClick(e) {
        if(! e) e = window.event;
        var t = e.target;
        if(t.innerHTML == 'Delete') {
            return eDeletePage(t.id);
        }
        else if(t.innerHTML == 'Clear') {
            return eClearPage(t.id);
        }
        else if(t.innerHTML == 'Page log') {
            return ePageLog(t.id);
        }
        return true;
    }

    function CheckAll() {
        if(document.pagesform.ckall.checked) {
            eSelectAll();
        }
        else {
            eClearAll();
        }
    }

    function SetCheckboxes(val) {
        val = val ? 'checked' : '';
        pgchecks = $('tblpages').getElementsByTagName('input');
        for(var i = 0; i < pgchecks.length; i++) {
            pgchecks[i].checked = val;
        }
    }

    function eSelectAll() {
        SetCheckboxes(true);
    }

    function eClearAll() {
        SetCheckboxes(false);
    }

</script>
<?php
}


// vim: sw=4 ts=4 expandtab
?>

